import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';
import '../provide/child_category.dart';
import '../provide/setting.dart';
import '../provide/category_goods_list.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:dio/dio.dart';
import '../routes/application.dart';
import 'package:cached_network_image/cached_network_image.dart';

class CategoryPage extends StatefulWidget {
  final Widget child;

  CategoryPage({Key key, this.child}) : super(key: key);

  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(title: Text('商品分类'),),
       body: Container(
         child: Row(
           children: <Widget>[
             LeftCategoryNav(),
             Column(
               children: <Widget>[
                 RightCategoryNav(),
                 CategoryGoodsList()
               ],
             )
           ],
         ),
       ),
    );
  }
}

// 左侧导航大菜单
class LeftCategoryNav extends StatefulWidget {

  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list=[];// 大类列表
  var leftIndex = 0;
  @override
  void initState() {
    super.initState();
    _getCategory();
    // _getGoodsList();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
         width: ScreenUtil().setWidth(180),
         decoration: BoxDecoration(
           border: Border(
             right: BorderSide(width: 1,color: Colors.black12)
           )
         ),
         child: ListView.builder(
           itemCount: list.length,
           itemBuilder: (context,index){
             return _leftInkWel(index);
           },
         ),
       );
  }

  // 获取数据
  void _getCategory()async{
  Dio dio = new Dio();
  Response response = await dio.get('http://dianshan.free.idcfengye.com/goods/categoryList');
  var data = json.decode(response.toString());
  setState(() {
   list = data['message']; 
  });
  // 默认获取第一个大类的小类列表
  var formData = {
    'categorySubId': list[0]['ID']
  };
  response = await dio.post('http://dianshan.free.idcfengye.com/goods/categorySubList',data: formData);
  data = json.decode(response.toString());
  Provide.value<ChildCategory>(context).getChildCategory(data['message'],list[0]['ID']);
  _getGoodsList();
}

// 默认得到第一个大类第一个小类的商品具体列表数据
  void _getGoodsList({String categoryId})async {
    Dio dio = new Dio();
    var formData = {
      'categorySubId': categoryId != null?categoryId: Provide.value<ChildCategory>(context).childCategoryList[0]['ID'],
      'page':1
    };
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/getGoodsListByCategorySubId',data: formData);
    var data = json.decode(response.toString());
    Provide.value<CategoryGoodsListProvide>(context).getGoodsList(data['message']);
  }

  // 获取小类列表
  Future _getSubList(ID) async {
    Dio dio = new Dio();
    var formData = {
      'categorySubId': ID
    };
    // 获取小类列表
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/categorySubList',data: formData);
    return response.toString();
  }

// 返回大导航单项部件
Widget _leftInkWel(int index){
  bool isChecked = false;
  isChecked = (index == leftIndex) ? true : false;
  return InkWell(
    onTap: (){
      _getSubList(list[index]['ID']).then((val){
        var data = json.decode(val.toString());
        var categoryId= list[index]['ID'];// 大类 id
        Provide.value<ChildCategory>(context).getChildCategory(data['message'],categoryId);
        _getGoodsList(categoryId: data['message'][0]['ID']); // 获取具体数据
        Provide.value<ChildCategory>(context).changeChildIndex(0, data['message'][0]['ID']);
        
      });
      // 点击改变颜色
      setState(() {
       leftIndex=index; 
      });
    },
    child: Container(
      height: ScreenUtil().setHeight(100),
      padding: EdgeInsets.only(left: 10,top: 20),
      decoration: BoxDecoration(
        color: isChecked?Color.fromRGBO(236, 238, 239, 1.0):Colors.white,
        border: Border(
          bottom: BorderSide(width: 1,color: Colors.black12),
        )
      ),
      child: Text(list[index]['MALL_CATEGORY_NAME'],style: TextStyle(fontSize: ScreenUtil().setSp(28)),)
    ),
  );
}
}

// 右侧小类类别
class RightCategoryNav extends StatefulWidget {
  final Widget child;

  RightCategoryNav({Key key, this.child}) : super(key: key);

  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  //得到商品列表数据
   void _getGoodList(String categorySubId) {
     
    var data={
      'categoryId':Provide.value<ChildCategory>(context).categoryId,
      'categorySubId':categorySubId,
      'page':1
    };
    _getList(categorySubId).then((val){
      var data = json.decode(val.toString());
      Provide.value<CategoryGoodsListProvide>(context).getGoodsList(data['message']);
    });
  }

  Future _getList(ID) async {
    Dio dio = new Dio();
    var formData = {
      'categorySubId': ID
    };
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/getGoodsListByCategorySubId',data: formData);
    return response.toString();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Provide<ChildCategory>(
         builder: (ctx,child,childCategory){
           return Container(
         height: ScreenUtil().setHeight(80),
         width: ScreenUtil().setWidth(570),
         decoration: BoxDecoration(
           color: Colors.white,
           border: Border(
             bottom: BorderSide(width: 1,color: Colors.black12)
           )
         ),
         child: ListView.builder(
           scrollDirection: Axis.horizontal,
           itemCount: childCategory.childCategoryList.length,
           itemBuilder: (context,index){
             return _rightInkWell(index,childCategory.childCategoryList[index]);
           },
         ),
       );
         },
       )
    );
  }

  // 返回小类单部件
  Widget _rightInkWell(int index,item){
    bool isCheck = false;
    isCheck =(index==Provide.value<ChildCategory>(context).childIndex)?true:false;
    return InkWell(
      onTap: (){
        // 改变索引颜色
        Provide.value<ChildCategory>(context).changeChildIndex(index,item['ID']);
        // 点击根据小类 ID 获取商品数据
        _getGoodList(item['ID']);
      },
      child: Container(
        color:isCheck?Theme.of(context).primaryColor:Colors.white,
        padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
        child: Text(
          item['MALL_SUB_NAME'],
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }
}

// 商品列表 可以上拉加载
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {

  var scrollController = new ScrollController();  

  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsListProvide>(
        builder: (context,child,data){
          try{
            if(Provide.value<ChildCategory>(context).page==1){
              scrollController.jumpTo(0.0);
            }
          }catch(e){
            // 第一次进入页面还没有使用 scrollContoller 会报错，把错误 catch 掉
            print('进入页面第一次初始化');
          }
          if(data.goodsList.length>0){
             return Expanded(
                child:Container(
                  width: ScreenUtil().setWidth(570) ,
                  child:EasyRefresh(
                    refreshFooter: ClassicsFooter(
                      key: GlobalKey(),
                      bgColor:Colors.white,
                      textColor:Colors.pink,
                      moreInfoColor: Colors.pink,
                      showMore:true,
                      noMoreText:Provide.value<ChildCategory>(context).noMoreText,
                      moreInfo:'加载中',
                      loadReadyText:'上拉加载'
                    ),
                    child:ListView.builder(
                      controller: scrollController,
                      itemCount: data.goodsList.length,
                      itemBuilder: (context,index){
                        return _ListWidget(data.goodsList,index);
                      },
                    ) ,
                    loadMore: ()async{
                        _getMoreList();
                    },
                  )
                  
                ) ,
              ); 
          }else{
            return  Text('暂时没有数据');
          }
       },
    );
  }

//上拉加载更多的方法
  void _getMoreList()async{
     // 页数加一
    Provide.value<ChildCategory>(context).addPage();
     var data={
      'categoryId':Provide.value<ChildCategory>(context).categoryId,
      'categorySubId':Provide.value<ChildCategory>(context).subId,
      'page':Provide.value<ChildCategory>(context).page
    };
    Dio dio = new Dio();
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/getGoodsListByCategorySubId',data: data);
    var datajson = json.decode(response.toString());
    if(datajson['message'].length == 0){
      Fluttertoast.showToast(
        msg: "已经到底了",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      Provide.value<ChildCategory>(context).changeNoMore('没有更多了');
    }else{
          Provide.value<CategoryGoodsListProvide>(context).addGoodsList(datajson['message']);
        }
  }
 

  Widget _ListWidget(List newList,int index){
    return InkWell(
      onTap: (){
        Application.router.navigateTo(context,"/detail?id=${newList[index]['ID']}");
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0,bottom: 5.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.0,color: Colors.black12)
          )
        ),
        
        child: Row(
          children: <Widget>[
            _goodsImage(newList,index)
           ,
            Column(
              children: <Widget>[
                _goodsName(newList,index),
                _goodsPrice(newList,index)
              ],
            )
          ],
        ),
      )
    );

  }

  Widget _goodsImage(List newList,int index){
    
    return  Container(
      width: ScreenUtil().setWidth(200),
      child: Provide<SettingProvide>(
        builder: (context,child,val){
          return val.noImage?Image.asset('images/noImage.png')
                            :CachedNetworkImage(
                              imageUrl: newList[index]['IMAGE1'],
                              placeholder: (context, url) => Center(
                                child: Text('正在加载',style: TextStyle(color: Colors.white),),
                              ),
                              errorWidget: (context, url, error) => new Icon(Icons.error),
                              fit: BoxFit.contain,
                            );
        },
      ),
    );

  }
  

  Widget _goodsName(List newList,int index){
    return Container( 
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        newList[index]['NAME'],
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      );
  }

  Widget _goodsPrice(List newList,int index){
    return  Container( 
      margin: EdgeInsets.only(top:20.0),
      width: ScreenUtil().setWidth(370),
      child:Row(
        children: <Widget>[
            Text(
              '价格:￥${newList[index]['PRESENT_PRICE']}',
              style: TextStyle(color:Theme.of(context).primaryColor,fontSize:ScreenUtil().setSp(30)),
              ),
            Text(
              '￥${newList[index]['ORI_PRICE']}',
              style: TextStyle(
                color: Colors.black26,
                decoration: TextDecoration.lineThrough
              ),
            )
        ]
      )
    );
  }
}